package com.shf.service.impl;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shf.constants.SystemCanstants;
import com.shf.domain.entity.Article;
import com.shf.domain.entity.Comment;
import com.shf.domain.entity.User;
import com.shf.domain.vo.NotificationsVo;
import com.shf.mapper.CommentMapper;
import com.shf.service.ArticleService;
import com.shf.service.NotificationService;
import com.shf.service.UserService;
import com.shf.util.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 叶枫
 * @date 2024/4/29.
 */

@Service
public class NotificationServiceImpl extends ServiceImpl<CommentMapper, Comment> implements NotificationService {
    @Resource
    private UserService userService;
    @Resource
    private ArticleService articleService;
    @Override
    public List<NotificationsVo> getNotifications(Integer pageNum,Integer pageSize) {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //获取评论创建人等于当前用户id所有评论
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        //条件：必须是所有的根评论 未删除的
        queryWrapper.eq(userId != null,Comment::getCreateBy,userId)
                .eq(Comment::getRootId,SystemCanstants.COMMENT_ROOT);
        List<Comment> comments = baseMapper.selectList(queryWrapper);
        Set<Long> longSet = comments.stream().map(comment -> comment.getId())
                .collect(Collectors.toSet());
        //然后再查询跟评论 是上面查询结果的每个id;
        //先按照已读 和未读 排序 然后按照日期排序;
        LambdaQueryWrapper<Comment> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(Comment::getRootId,longSet)
                .orderByAsc(Comment::getStatus)
                .orderByDesc(Comment::getCreateTime);

        Page<Comment> page = new Page<>(pageNum, pageSize);
        Page<Comment> commentPage = page(page, queryWrapper1);

        Set<Long> articleIds = commentPage.getRecords().stream().map(comment -> comment.getArticleId())
                .collect(Collectors.toSet());

        List<NotificationsVo> collect = commentPage.getRecords().stream()
                .map(comment -> {
                    NotificationsVo notificationsVo = CopyVo(comment);
                    notificationsVo.setPageNum((int) commentPage.getCurrent());
                    notificationsVo.setPageSize((int) commentPage.getSize());
                    notificationsVo.setTotal(commentPage.getTotal());
                    Map<Long, String> articleNameMap = getArticleName(articleIds);
                    notificationsVo.setArticleName(articleNameMap.get(notificationsVo.getArticleId()));

                    return notificationsVo;
                })
                .collect(Collectors.toList());

        return collect;
    }

    private Map<Long,String> getArticleName(Set<Long> articleIds){
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","title")
                .eq("status",SystemCanstants.ARTICLE_STATUS_NORMAL);
        if (articleIds.size()>0){
            queryWrapper.in("id",articleIds);
            List<Article> articles = articleService.list(queryWrapper);
            Map<Long, String> collect = articles.stream().collect(Collectors.toMap(Article::getId, Article::getTitle));
            return collect;
        }
        return null;
    }
    private NotificationsVo CopyVo(Comment comment){
        NotificationsVo notificationsVo = new NotificationsVo();

        String type = comment.getType();
        Long articleId = comment.getArticleId();
        String content = comment.getContent();
        Long toCommentUserId = comment.getToCommentUserId();
        Long toCommentId = comment.getToCommentId();
        Integer status = comment.getStatus();

        User byId = userService.getById(toCommentUserId);

        notificationsVo.setContent(content);
        notificationsVo.setType(type);
        notificationsVo.setArticleId(articleId);
        notificationsVo.setToCommentUserId(toCommentUserId);
        notificationsVo.setToCommentId(toCommentId);
        notificationsVo.setStatus(status);
        notificationsVo.setToCommentUserName(byId.getUserName());
        notificationsVo.setCreateTime(comment.getCreateTime());
        return notificationsVo;
    }
}
